package com.example.rbm;

import com.example.consts.RbmConsts;
import com.example.service.SavePosClickService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 本文来演示
 *
 * @author 赵建云
 * @create 2023/10/13
 */
@Component
public class RbmClick {
    @Autowired
    private SavePosClickService savePosClickService;
    @Autowired
    private RedisTemplate redisTemplate;
    @RabbitHandler
    @RabbitListener(queues = RbmConsts.ROOTING_DH_CLICK)
    public void saveClick(String click, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG)long tag) throws IOException {
        int count = 5;
        boolean flag = false;
        ValueOperations vop = redisTemplate.opsForValue();
        String uuid = UUID.randomUUID().toString();
        while (!flag&&(count--)>0){
            try {
                if (redisTemplate.hasKey(uuid)){
                    System.out.println("已经点击过");
                    channel.basicAck(tag,false);
                    return;
                }
                String[] cli = click.split(",");
                System.out.println(Arrays.toString(cli));
                Integer jsId = Integer.valueOf(cli[0]);
                Integer posId = Integer.valueOf(cli[1]);
                System.out.println("click="+jsId+":"+posId);
                flag=true;
                System.out.println("========");
                vop.set(uuid,uuid);
                redisTemplate.expire(uuid,10,TimeUnit.SECONDS);
                savePosClickService.savePosClick(jsId,posId);
                channel.basicAck(tag,false);
            } catch (Exception e) {
                System.out.println("重试");
            }
        }
        if (!flag){
            System.out.println("没走。。。。。");
            channel.basicNack(tag,false,false);
        }

    }
}
